// 获取滚动条

const ApiScroll = {
    /**
     * 
     * @desc 获取滚动条距顶部的距离
     */
    getScrollTop() {
        return (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    },
    /**
     * 
     * @desc  在${duration}时间内，滚动条平滑滚动到${to}指定位置
     * @param {Number} to 
     * @param {Number} duration 
     */
    scrollTo(to, duration) {
        if (duration < 0) {
            this.setScrollTop(to);
            return
        }
        var diff = to - this.getScrollTop();
        if (diff === 0) return
        var step = diff / duration * 10;
        requestAnimationFrame(
            function () {
                if (Math.abs(step) > Math.abs(diff)) {
                    this.setScrollTop(this.getScrollTop() + diff);
                    return;
                }
                this.setScrollTop(this.getScrollTop() + step);
                if (diff > 0 && this.getScrollTop() >= to || diff < 0 && this.getScrollTop() <= to) {
                    return;
                }
                scrollTo(to, duration - 16);
            });
    },
    /**
     * 
     * @desc 设置滚动条距顶部的距离
     */
    setScrollTop(value) {
        window.scrollTo(0, value);
        return value;
    },

    /**
     * 
     * @desc  获取一个元素的距离文档(document)的位置，类似jQ中的offset()
     * @param {HTMLElement} ele 
     * @returns { {left: number, top: number} }
     */
    offset(ele) {
        var pos = {
            left: 0,
            top: 0
        };
        while (ele) {
            pos.left += ele.offsetLeft;
            pos.top += ele.offsetTop;
            ele = ele.offsetParent;
        };
        return pos;
    }
}


export default ApiScroll